/**
 * @author Ali Koudri - ali.koudri@thalesgroup.com
 */

package org.obeonetwork.dsl.spem.extension.spem_ifest.dashboard;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.draw2d.IFigure;
import org.eclipse.emf.common.ui.dialogs.WorkspaceResourceDialog;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.ui.dialogs.FileSelectionDialog;
import org.eclipse.ui.dialogs.FileSystemElement;
import org.obeonetwork.dsl.spem.MethodLibrary;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.xml.sax.SAXException;

public class DashboardMediator {

	private static final boolean STRICT = true;

	private DashboardFigure view;

	private IProject project;
	
	private DashboardPart part;

	public DashboardMediator(DashboardPart part) {
		this.part = part;
	}

	public boolean isStrict() {
		return STRICT;
	}

	public void setView(DashboardFigure view) {
		this.view = view;
		view.getMethodoFigure().getStructureFigure().addAction(createLinkFigure("Create methodology structure", new CreateSpemModelAction()));
		view.getMethodoFigure().getIfestFigure().addAction(createLinkFigure("Import ifest framework", new ImportIFESTFramworkAction()));
		view.getMethodoFigure().getTasksFigure().addAction(createLinkFigure("Define tasks", new NullAction()));
		view.getProcessFigure().getStructureFigure().addAction(createLinkFigure("Create process structure", new NullAction()));
		view.getProcessFigure().getActivitiesFigure().addAction(createLinkFigure("Capture activities", new NullAction()));
		view.getProcessFigure().getWorkflowFigure().addAction(createLinkFigure("Capture workflow", new NullAction()));
		updateStatus();
	}

	/**
	 * Also initializes the action.
	 */
	protected IFigure createLinkFigure(String text, DashboardAction action) {
		HyperlinkFigure linkFigure = new HyperlinkFigure(action);
		linkFigure.setText(text);
		return linkFigure;
	}

	public IProject getProject() {
		return project;
	}

	public void setProjectAndState(IProject project) {
		this.project = project;
		updateStatus();
	}

	public void updateStatus() {
		if (project == null) {
			view.getStatusLine(0).setText("Select the project");
		} else {
			view.getStatusLine(0).setText(MessageFormat.format("Project", new Object[] { project.getName() }));
		}
		view.repaint(); // update hyperlinks
	}

	protected void setModelName(ModelFigure figure, URI uri) {
		figure.setName(uri == null ? null : uri.lastSegment());
		figure.setFullName(uri == null ? null : uri.toString());
	}
	
	protected class CreateSpemModelAction implements DashboardAction
	{
		private boolean enabled = true;

		public boolean isEnabled() {
			// TODO Auto-generated method stub
			return enabled;
		}

		public void run() {
			IStructuredSelection selection = part.getSelection();
			if (selection == null) return;
			//enabled = false;
			SpemModelWizard wizard = new SpemModelWizard();
			wizard.init(part.getSite().getWorkbenchWindow().getWorkbench(), selection);
			WizardDialog dialog = new WizardDialog(part.getSite().getShell(), wizard);
			dialog.create();
			dialog.open();
			
		}
		
	}
	//CHanh Duc
	protected class ImportIFESTFramworkAction implements DashboardAction
	{
		private boolean enabled = true;
		public boolean isEnabled() {
			// TODO Auto-generated method stub
			return enabled;
		}

		public void run() {
			// TODO Auto-generated method stub
			/*
			IStructuredSelection selection = part.getSelection();
			//if (selection == null) return;
			//if (selection.size()!=1) return;
			List<ViewerFilter> filters = new ArrayList<ViewerFilter>();
			filters.add(new ViewerFilter() {
							@Override
				public boolean select(Viewer viewer, Object parentElement,
						Object element) {
					// TODO Auto-generated method stub
					   if (element instanceof IFile) {
				            return ((IFile)element).
				                getFileExtension().equals("spem_ifest");
				        } else return true;
				}
			});
			//Select model
			IFile[] files = WorkspaceResourceDialog.openFileSelection(part.getSite().getShell(), "select file", "", false, null, filters);
			if (files==null) return;
			//Load model
			IFile modelFile = files[0];
			ResourceSet rset = new ResourceSetImpl();
			URI fURI = URI.createPlatformResourceURI(modelFile.getFullPath().toString(), true);
			Resource r = rset.getResource(fURI, true);
			MethodLibrary lib = (MethodLibrary) r.getContents().get(0);
			IFESTImport ifestImport = new IFESTImport();
			boolean rs;
			try {
				rs = ifestImport.generatePackage(lib);
				if (rs==false)
				{
				MessageBox mssbox = new MessageBox(part.getSite().getShell());
				mssbox.setMessage("Model null");
				mssbox.open();
				return;
				}
				rs = ifestImport.importToModel(new MethodLibrary[] {lib});
				if (rs==false)
				{
				MessageBox mssbox = new MessageBox(part.getSite().getShell());
				mssbox.setMessage("import failed");
				mssbox.open();
				return;
				}
				//save model
				try {
					r.save(null);
					MessageBox mssbox = new MessageBox(part.getSite().getShell());
					mssbox.setMessage("Successfully");
					mssbox.open();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			} catch (OWLOntologyCreationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			*/
			
		}
		
	}
	
	protected class NullAction implements DashboardAction
	{
		public boolean isEnabled() {
			// TODO Auto-generated method stub
			return false;
		}

		public void run() {
			System.out.println("Action not implemented");
		}
		
	}

	public IProject getActiveProject() {
		// TODO Auto-generated method stub
		return null;
	}

}
